#!/usr/bin/env python3
"""
Proxy configuration management for IDEA Proxy Monitor
"""
import json
import os
from pathlib import Path

class ProxyConfig:
    def __init__(self, config_file='proxy_config.json'):
        self.config_file = Path(config_file)
        self.config = self._load_config()
    
    def _load_config(self):
        """Load configuration from file"""
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r') as f:
                    return json.load(f)
            except Exception as e:
                print(f"Error loading config: {e}")
        return self._default_config()
    
    def _default_config(self):
        """Default configuration"""
        return {
            'proxy': {
                'host': '127.0.0.1',
                'port': 8080
            },
            'dashboard': {
                'enabled': True,
                'port': 8081
            },
            'upstream_proxy': {
                'enabled': False,
                'host': '',
                'port': 0,
                'username': '',
                'password': ''
            },
            'ssl': {
                'generate_certs': False,
                'cert_dir': './certs'
            }
        }
    
    def save_config(self):
        """Save configuration to file"""
        try:
            with open(self.config_file, 'w') as f:
                json.dump(self.config, f, indent=4)
            return True
        except Exception as e:
            print(f"Error saving config: {e}")
            return False
    
    def get_upstream_proxy_config(self):
        """Get upstream proxy configuration"""
        upstream = self.config.get('upstream_proxy', {})
        if not upstream.get('enabled', False):
            return None
        
        config = {
            'host': upstream.get('host', ''),
            'port': upstream.get('port', 0),
            'username': upstream.get('username', ''),
            'password': upstream.get('password', '')
        }
        
        # Only return config if host and port are provided
        if config['host'] and config['port']:
            return config
        return None
    
    def set_upstream_proxy(self, host, port, username=None, password=None):
        """Set upstream proxy configuration"""
        self.config['upstream_proxy'] = {
            'enabled': True,
            'host': host,
            'port': int(port),
            'username': username or '',
            'password': password or ''
        }
        return self.save_config()
    
    def disable_upstream_proxy(self):
        """Disable upstream proxy"""
        self.config['upstream_proxy']['enabled'] = False
        return self.save_config()
    
    def get_proxy_config(self):
        """Get main proxy configuration"""
        return self.config.get('proxy', {'host': '127.0.0.1', 'port': 8080})
    
    def set_proxy_config(self, host, port):
        """Set main proxy configuration"""
        self.config['proxy'] = {
            'host': host,
            'port': int(port)
        }
        return self.save_config()
    
    def get_dashboard_config(self):
        """Get dashboard configuration"""
        return self.config.get('dashboard', {'enabled': True, 'port': 8081})
    
    def export_idea_proxy_config(self):
        """Export configuration for IDEA proxy setup"""
        proxy_config = self.get_proxy_config()
        return {
            'host': proxy_config['host'],
            'port': proxy_config['port']
        }

if __name__ == '__main__':
    # Configuration management CLI
    import sys
    
    config = ProxyConfig()
    
    if len(sys.argv) < 2:
        print("Usage: python3 proxy_config.py <command> [args...]")
        print("Commands:")
        print("  show                    - Show current configuration")
        print("  set-upstream HOST PORT [USERNAME] [PASSWORD] - Set upstream proxy")
        print("  disable-upstream        - Disable upstream proxy")
        print("  set-proxy HOST PORT     - Set main proxy configuration")
        sys.exit(1)
    
    command = sys.argv[1]
    
    if command == 'show':
        print("Current Configuration:")
        print(json.dumps(config.config, indent=2))
    
    elif command == 'set-upstream':
        if len(sys.argv) < 4:
            print("Usage: set-upstream HOST PORT [USERNAME] [PASSWORD]")
            sys.exit(1)
        
        host = sys.argv[2]
        port = int(sys.argv[3])
        username = sys.argv[4] if len(sys.argv) > 4 else None
        password = sys.argv[5] if len(sys.argv) > 5 else None
        
        if config.set_upstream_proxy(host, port, username, password):
            print(f"Upstream proxy configured: {host}:{port}")
            if username:
                print(f"Authentication: {username}")
        else:
            print("Failed to save configuration")
    
    elif command == 'disable-upstream':
        if config.disable_upstream_proxy():
            print("Upstream proxy disabled")
        else:
            print("Failed to save configuration")
    
    elif command == 'set-proxy':
        if len(sys.argv) < 4:
            print("Usage: set-proxy HOST PORT")
            sys.exit(1)
        
        host = sys.argv[2]
        port = int(sys.argv[3])
        
        if config.set_proxy_config(host, port):
            print(f"Proxy configured: {host}:{port}")
        else:
            print("Failed to save configuration")
    
    else:
        print(f"Unknown command: {command}")
        sys.exit(1)